<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="queryParams.username" placeholder="输入用户名或昵称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="queryParams.nickname" placeholder="输入用户名或昵称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="所属评论" prop="commentId">
        <el-input v-model="queryParams.commentId" placeholder="请输入所属评论id" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="所属动态" prop="dynamicId">
        <el-input v-model="queryParams.dynamicId" placeholder="请输入所属动态id" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="时间范围" style="width: 308px">
        <el-date-picker v-model="dateRange" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[
            new Date(2000, 0, 1, 0, 0, 0),
            new Date(2000, 0, 1, 23, 59, 59)
          ]" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['like:like:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['like:like:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['like:like:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['like:like:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="likeList" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="点赞编号" align="center" prop="likeId" />
      <el-table-column label="用户名" align="center" prop="username"></el-table-column>
      <el-table-column label="昵称" align="center" prop="nickname"></el-table-column>
      <el-table-column label="所属评论" align="center" prop="commentId" />
      <el-table-column label="所属动态" align="center" prop="dynamicId" />
      <el-table-column label="点赞时间" align="center" prop="likeTime" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ parseTime(scope.row.likeTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['like:like:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['like:like:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改点赞功能对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="likeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="点赞用户" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入点赞的用户id" @blur="exit" />
        </el-form-item>
        <el-form-item label="所属动态" prop="dynamicId">
          <el-input v-model="form.dynamicId" placeholder="请输入所属动态id" @blur="checkDynamic(form.dynamicId)" />
        </el-form-item>
        <el-form-item label="所属评论" prop="commentId">
          <el-input v-model="form.commentId" placeholder="请输入所属评论id" @blur="commentExit(form.commentId)" />
        </el-form-item>
        <!-- <el-form-item label="点赞时间" prop="likeTime">
          <el-date-picker clearable v-model="form.likeTime" type="date" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择点赞时间">
          </el-date-picker> -->
        <!-- </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :disabled="!form.userId">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Like">
import { listLike, getLike, delLike, addLike, updateLike } from "@/api/like/like"
import { getUsers } from '@/api/users/users'
import { checkDynamicExists } from "@/api/dynamic/dynamic"
import { checkCommentExit } from "../../../api/comment/comment"
import request from '@/utils/request';

const { proxy } = getCurrentInstance()

const likeList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dateRange = ref([])


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    commentId: null,
    dynamicId: null,
    likeTime: null,
    nickname: null,
    username: null,
    beginTime: null, // Add for start of date range
    endTime: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询点赞功能列表 */
function getList() {
  loading.value = true
  listLike(queryParams.value).then(response => {
    likeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

function commentExit(commentId) {
  // 允许commentId为0，但必须传递
  if (commentId === null || commentId === undefined || commentId === '') {
    console.log("评论ID不能为空")
    return Promise.resolve(false)
  }

  // 转换为数字（允许0）
  const id = Number(commentId)
  if (isNaN(id)) {
    proxy.$modal.msgError("评论ID必须是数字")
    return Promise.resolve(false)
  }
  // 若commentId为0，检查dynamicId是否为0
  if (id === 0) {
    if (form.value.dynamicId === 0) {
      proxy.$modal.msgError("评论ID为0时，动态ID不能同时为0")
      form.value.commentId = ""
      return false
    }
    return Promise.resolve(true)
  }
  return checkCommentExit(id).then(res => {
    // 关键修改：直接使用res.data获取布尔值
    const exists = res.data;
    if (!exists) {
      proxy.$modal.msgError("评论不存在")
      form.value.commentId = ""
    }
    return exists
  }).catch(error => {
    console.error("检查评论失败:", error)
    proxy.$modal.msgError("检查评论失败")
    return false
  })
}

function exit() {
  const userId = form.value.userId;
  // 空值检查
  if (!userId) {
    console.log("用户ID为空");
    return;
  }
  // 转换为数字并检查
  const numUserId = Number(userId);
  if (isNaN(numUserId)) {
    proxy.$modal.msgError("用户ID必须是数字");
    form.value.userId = ""; // 清空非数字输入
    return;
  }
  getUsers(userId).then(res => {
    if (res.data === undefined) {
      proxy.$modal.msgError("用户不存在")
      form.value.userId = ""
    }
  })
}

// 表单重置
function reset() {
  form.value = {
    likeId: null,
    userId: null,
    commentId: null,
    dynamicId: null,
    likeTime: null,
    nickname: null,
    username: null
  }
  proxy.resetForm("likeRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log(dateRange.value)
  // 设置日期范围参数
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.beginTime = dateRange.value[0];
    queryParams.value.endTime = `${dateRange.value[1]} 23:59:59`;
  } else {
    queryParams.value.beginTime = null;
    queryParams.value.endTime = null;
  }
  console.log(queryParams.value)
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [] // Reset date range
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.likeId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加点赞功能"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _likeId = row.likeId || ids.value
  getLike(_likeId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改点赞功能"
  })
}

function checkDynamic(dynamicId) {
  // 允许dynamicId为0，但必须传递
  if (dynamicId === null || dynamicId === undefined || dynamicId === '') {
    console.log("动态ID不能为空")
    return Promise.resolve(false)
  }

  const id = Number(dynamicId)
  if (isNaN(id)) {
    proxy.$modal.msgError("动态ID必须是数字")
    return Promise.resolve(false)
  }

  // **新增：若dynamicId为0，检查commentId是否为0**
  if (id === 0) {
    if (form.value.commentId === 0) {
      proxy.$modal.msgError("动态ID为0时，评论ID不能同时为0")
      form.value.dynamicId = ""
      return false
    }
    return Promise.resolve(true)
  }

  return checkDynamicExists(id).then(res => {
    if (!res.data) {
      proxy.$modal.msgError("动态不存在")
      form.value.dynamicId = ""
      return false
    }
    return true
  }).catch(error => {
    console.error("检查动态失败:", error)
    proxy.$modal.msgError("检查动态失败，请稍后再试")
    return false
  })
}

// 前端重复点赞校验
function checkDuplicateLike(userId, dynamicId, commentId) {
  if (!userId || (dynamicId === 0 && commentId === 0)) {
    return Promise.resolve(false);
  }

  return request({
    url: '/like/like/checkDuplicate',
    method: 'get',
    params: {
      userId: userId,
      dynamicId: dynamicId,
      commentId: commentId
    }
  }).then(res => {
    return res.data;
  }).catch(error => {
    // 屏蔽参数类型错误，其他错误正常抛出
    if (error.message.includes("参数[userId]要求类型为")) {
      console.log("参数类型错误已屏蔽");
      return false;
    }
    throw error;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["likeRef"].validate(valid => {
    if (valid) {
      // 转换dynamicId和commentId为数字，避免null/undefined导致的误判
      const dynamicId = Number(form.value.dynamicId)
      const commentId = Number(form.value.commentId)

      if (dynamicId === 0 && commentId === 0) {
        proxy.$modal.msgError("动态ID和评论ID不能同时为0")
        return
      }

      // 新增：前端重复点赞校验
      checkDuplicateLike(form.value.userId, dynamicId, commentId).then(exist => {
        if (exist) {
          proxy.$modal.msgError("不能重复点赞，请先取消之前的点赞");
          return;
        }

        if (form.value.likeId != null) {
          updateLike(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addLike(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _likeIds = row.likeId || ids.value
  proxy.$modal.confirm('是否确认删除点赞功能编号为"' + _likeIds + '"的数据项？').then(function () {
    return delLike(_likeIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('like/like/export', {
    ...queryParams.value
  }, `like_${new Date().getTime()}.xlsx`)
}

getList()
</script>
